package com.ravi.interceptors;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ravi.common.R;
import com.ravi.exception.ErrorCode;
import com.ravi.util.jwt.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("token");
		R r;
		try {
			JWTUtils.verify(token);
			return true;
		}catch (TokenExpiredException e){
			r = R.error(ErrorCode.TOKEN_EXPIRED, "token过期!");
		}catch (Exception e){
			r = R.error(ErrorCode.TOKEN_ERROR,"token错误!");
		}
		String json = new ObjectMapper().writeValueAsString(r);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().print(json);
		return false;
	}
}
